﻿// --------------------------------------------------------------------------------------------------------------------
// <copyright file="CurrenciesForm.cs" company="">
//   
// </copyright>
// <summary>
//   The currencies form.
// </summary>
// --------------------------------------------------------------------------------------------------------------------


using System;
using System.Collections.Generic;
using System.Data.Objects;
using System.Data.Objects.DataClasses;
using System.Linq;
using System.Windows.Forms;
using Systemathics.FrameWork;

namespace Systemathics.UserControls
{
    /// <summary>
    /// The currencies form.
    /// </summary>
    public partial class CurrenciesForm : Form
    {
        /// <summary>
        /// The db.
        /// </summary>
        private SystemathicsEntities db;

        /// <summary>
        /// The last selected data grid view row.
        /// </summary>
        private DataGridViewRow lastSelectedDataGridViewRow;

        /// <summary>
        /// Initializes a new instance of the <see cref="CurrenciesForm"/> class.
        /// </summary>
        public CurrenciesForm()
        {
            InitializeComponent();
        }

        /// <summary>
        /// The currencies form_ load.
        /// </summary>
        /// <param name="sender">
        /// The sender.
        /// </param>
        /// <param name="e">
        /// The e.
        /// </param>
        private void CurrenciesForm_Load(object sender, EventArgs e)
        {
            db = new SystemathicsEntities(GlobalVariables.EntitiesConnectionString());
            db.AcceptAllChanges();
            dBCurrencyBindingSource.DataSource = db.DBCurrency.Execute(MergeOption.AppendOnly);
        }

        /// <summary>
        /// The currency data grid view_ cell click.
        /// </summary>
        /// <param name="sender">
        /// The sender.
        /// </param>
        /// <param name="e">
        /// The e.
        /// </param>
        private void CurrencyDataGridView_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            try
            {
                lastSelectedDataGridViewRow = ((DataGridView) sender).Rows[e.RowIndex];
                var dbi = (DBCurrency) lastSelectedDataGridViewRow.DataBoundItem;

                dbi.DBInstruments.Load();
                var temp = new List<string>();
                foreach (DBInstruments t in dbi.DBInstruments)
                    temp.Add(t.Name);

                Grid.SelectedObject = new OverridedDBCurrency
                                          {
                                              ID = dbi.ID, 
                                              CurrencyName = dbi.CurrencyName, 
                                              Country = dbi.Country, 
                                              ReferencePrice = (double) dbi.ReferencePrice, 
                                              Ticker = dbi.Ticker, 
                                              InstrumentsCollection = temp
                                          };
            }
            catch (Exception)
            {
            }
        }

        /// <summary>
        /// The update_ click.
        /// </summary>
        /// <param name="sender">
        /// The sender.
        /// </param>
        /// <param name="e">
        /// The e.
        /// </param>
        private void Update_Click(object sender, EventArgs e)
        {
            SetCurrency(Grid);
        }

        /// <summary>
        /// The set currency.
        /// </summary>
        /// <param name="Grid">
        /// The grid.
        /// </param>
        private void SetCurrency(PropertyGrid Grid)
        {
            var i = Grid.SelectedObject as OverridedDBCurrency;
            var curr = new DBCurrency();
            if (i.ReferencePrice != 0 && i.Ticker != String.Empty && i.CurrencyName != String.Empty)
            {
                if (i.ID == null)
                {
                    curr.ID = Guid.NewGuid();
                    curr.DBInstruments = new EntityCollection<DBInstruments>();
                }
                else
                {
                    curr = db.DBCurrency.Where(p => p.ID.CompareTo((Guid) i.ID) == 0).FirstOrDefault();

                    // curr.DBInstruments.Load();
                    // foreach (var t in curr.DBInstruments.Take(curr.DBInstruments.Count).ToArray())
                    // curr.DBInstruments.Remove(t);
                }

                if (curr.Ticker != String.Empty)
                {
                    curr.Country = i.Country;
                    curr.CurrencyName = i.CurrencyName;
                    if (i.ReferencePrice < 0 || i.ReferencePrice == 0)
                    {
                        i.ReferencePrice = 1;
                        MessageBox.Show("Reference price not valid");
                    }

                    curr.ReferencePrice = i.ReferencePrice;
                    if (i.Ticker.Length > 3)
                    {
                        MessageBox.Show("Currency Ticker Must Not exceed 3 Characters.");
                        return;
                    }

                    curr.Ticker = i.Ticker;

                    try
                    {
                        db.AddToDBCurrency(curr);
                    }
                    catch
                    {
                    }

                    db.SaveChanges(true);
                    // dBCurrencyBindingSource.DataSource = db.DBInstruments.Execute(MergeOption.AppendOnly);
                }
            }
        }

        /// <summary>
        /// The add item_ click.
        /// </summary>
        /// <param name="sender">
        /// The sender.
        /// </param>
        /// <param name="e">
        /// The e.
        /// </param>
        private void AddItem_Click(object sender, EventArgs e)
        {
            Grid.SelectedObject = new OverridedDBCurrency();
        }

        /// <summary>
        /// The delete item_ click.
        /// </summary>
        /// <param name="sender">
        /// The sender.
        /// </param>
        /// <param name="e">
        /// The e.
        /// </param>
        private void DeleteItem_Click(object sender, EventArgs e)
        {
            if (lastSelectedDataGridViewRow == null)
                return;

            int index = lastSelectedDataGridViewRow.Index;
            object o = lastSelectedDataGridViewRow.DataBoundItem;
            db.DeleteObject(o);
            db.SaveChanges(true);
            lastSelectedDataGridViewRow = CurrencyDataGridView.Rows[index];
        }

        /// <summary>
        /// The excel item_ click.
        /// </summary>
        /// <param name="sender">
        /// The sender.
        /// </param>
        /// <param name="e">
        /// The e.
        /// </param>
        private void ExcelItem_Click(object sender, EventArgs e)
        {
            CurrencyDataGridView.SelectAll();
            DataObject d = CurrencyDataGridView.GetClipboardContent();
            Clipboard.SetDataObject(d);
            MessageBox.Show("Currencies Copied To ClipBorad", "Copy Orders", MessageBoxButtons.OK);
        }

        /// <summary>
        /// The on handle destroyed.
        /// </summary>
        /// <param name="e">
        /// The e.
        /// </param>
        protected override void OnHandleDestroyed(EventArgs e)
        {
            db.Dispose();
            base.OnHandleDestroyed(e);
        }
    }
}